package com.xiaoyu.base.event;

import in.srain.cube.app.lifecycle.LifeCycleComponent;

public class SimpleEventHandler implements LifeCycleComponent {

    private boolean mRegistered = false;
    private boolean mIsNull = false;

    public synchronized SimpleEventHandler tryToUnregister() {
        if (mRegistered) {
            mRegistered = false;
            AppEventBus.getInstance().unregister(this);
        }
        return this;
    }

    public synchronized SimpleEventHandler tryToRegisterIfNot() {
        if (!mRegistered) {
            mRegistered = true;
            if (mIsNull) {
                return this;
            }
            AppEventBus.getInstance().register(this);
        }
        return this;
    }

    public synchronized SimpleEventHandler tryToUnregisterWithNull() {
        mIsNull = true;
        tryToUnregister();
        return this;
    }

    @Override
    public void onBecomesPartiallyInvisible() {
    }

    @Override
    public void onBecomesVisible() {
        tryToRegisterIfNot();
    }

    @Override
    public void onBecomesTotallyInvisible() {
    }

    @Override
    public void onBecomesVisibleFromTotallyInvisible() {
    }

    @Override
    public void onDestroy() {
        tryToUnregister();
    }
}